import 'dart:async';
import 'dart:convert';
import 'package:web_socket_client/web_socket_client.dart' as ws;

import '../../../utils/tips.dart';

class AudioTranslateService {
  ws.WebSocket? audioTranlateSocket;
  bool wsServerHaveReady = false;
  final socketUrl = 'wss://xy-apis.newtranx.com/mt/v1/realtime';
  bool isPlaying = false;
  Timer? _timer;

  void initSocket(calback) {
    print('initsocket');
    if (audioTranlateSocket == null) {
      try {
        audioTranlateSocket = ws.WebSocket(
          Uri.parse(socketUrl),
          headers: {'x-api-key': '264e03da4958e5ea405dd8f63b87da898757b821'},
          timeout: Duration(seconds: 20)
        );

        audioTranlateSocket!.messages.listen(
          (v) {
            print('checkWebSocket${v}');
            if(v=='pong') return;
            if (v == 'ok') return;
            Map result = json.decode(v.toString());
            if (result['action'] == 'started') {
              print('checksocketstart');
              isPlaying = true;
              //发送心跳包.
              _timer = Timer.periodic(Duration(seconds: 12), (timer) {
                print('checkaudioTranlateSocket');
                if(audioTranlateSocket != null)
                  print('sendping');
                  audioTranlateSocket!.send('ping'); //
              });
            }
            if (result['sessionId'] != null) {
              calback(result);
            }
          },
          onError: (error) {
            Tips.showToast('WebSocket error: $error');
            print('WebSocket error: $error');
          },
          onDone: () {
            // 连接关闭时调用
            print('WebSocket connection closed.');
            if(isPlaying){
            //  如果app端还没主动断开连接需要重连
              sendClose();
              initSocket(calback);
            }
            if(_timer != null){
              _timer!.cancel();
            }
          },
        );
      } catch (e) {
        Tips.showToast('catch${e}');
        print('catch${e}');
      }
    }
  }

  Future<void> sendData(data) async {
    print('checksockedata${data}');
    if (isPlaying) {
      audioTranlateSocket!.send(data);
    }
  }

  Future<void> sendClose() async {
    if (audioTranlateSocket != null) {
      print('send end');
      audioTranlateSocket!.send(json.encode({"action": "end"}));
      // audioTranlateSocket = null;
      isPlaying=false;
      audioTranlateSocket!.close();
    }
  }
}
